<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">设备位置管理</span>
          <el-button v-hasPermi="['device:location:add']" type="primary" plain icon="Plus" @click="handleAdd">新增位置</el-button>
        </div>
      </template>

      <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="位置名称" prop="locationName">
          <el-input v-model="queryParams.locationName" placeholder="请输入位置名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="设备" prop="deviceId">
          <el-select
            v-model="queryParams.deviceId"
            placeholder="请选择设备"
            clearable
            style="width: 200px"
            filterable
            remote
            :remote-method="handleDeviceSearch"
            :loading="deviceLoading"
            @scroll="handleDeviceScroll"
          >
            <el-option v-for="device in deviceOptions" :key="device.id" :label="device.deviceName" :value="device.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-hasPermi="['device:location:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
            >删除</el-button
          >
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
      </el-row>

      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="locationList"
          border
          stripe
          highlight-current-row
          class="location-table"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="45" align="center" fixed="left" />
          <el-table-column label="位置ID" align="center" prop="id" min-width="80" />
          <el-table-column label="位置名称" align="center" prop="location" min-width="120" show-overflow-tooltip />
          <el-table-column label="详细地址" align="center" prop="address" min-width="200" show-overflow-tooltip />
          <el-table-column label="经度" align="center" prop="longitude" min-width="100" />
          <el-table-column label="纬度" align="center" prop="latitude" min-width="100" />
          <el-table-column label="状态" align="center" prop="status" min-width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template #default="scope">
              <el-button v-hasPermi="['device:location:view']" type="info" link icon="View" @click="handleView(scope.row)">查看</el-button>
              <el-button
                v-if="scope.row.status === 2"
                v-hasPermi="['device:location:edit']"
                type="primary"
                link
                icon="Edit"
                @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
              <el-button v-hasPermi="['device:location:remove']" type="danger" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <pagination
            v-if="total > 0"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="Location">
import { listLocation, getLocation, delLocation, addLocation, updateLocation, delBatchLocation } from '@/api/vending/location';
import type { LocationQuery, LocationForm, LocationVo } from '@/api/vending/location/types';
import { ref, getCurrentInstance, onMounted } from 'vue';
import type { FormInstance } from 'element-plus';
import { getlistDevice } from '@/api/vending/device';
import type { DeviceVO, DeviceQuery } from '@/api/vending/device/types';

const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<number[]>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 位置表格数据
const locationList = ref<LocationVo[]>([]);

// 表单ref
const queryRef = ref<FormInstance>();

// 查询参数
const queryParams = ref<LocationQuery>({
  pageNum: 1,
  pageSize: 10,
  locationName: undefined,
  deviceId: undefined
});

// 状态处理函数
const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'info'; // 撤销
    case 2:
      return 'warning'; // 草稿
    case 3:
      return 'warning'; // 待审核
    case 4:
      return 'success'; // 已完成
    case 5:
      return 'danger'; // 已作废
    case 6:
      return 'danger'; // 已退回
    case 7:
      return 'danger'; // 已终止
    default:
      return 'info';
  }
};

const getStatusLabel = (status: number) => {
  switch (status) {
    case 1:
      return '已撤销';
    case 2:
      return '草稿';
    case 3:
      return '待审核';
    case 4:
      return '已完成';
    case 5:
      return '已作废';
    case 6:
      return '已退回';
    case 7:
      return '已终止';
    default:
      return '未知状态';
  }
};

/** 查询位置列表 */
function getList() {
  loading.value = true;
  listLocation(queryParams.value).then((response) => {
    console.log(response)
    locationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: LocationVo[]) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push({ path: '/vending/locationEdit/index', query: { type: 'add' } });
}

/** 查看按钮操作 */
function handleView(row: LocationVo) {
  proxy.$router.push({ path: '/vending/locationEdit/index', query: { type: 'view', id: row.id } });
}

/** 删除按钮操作 */
function handleDelete(row?: LocationVo) {
  const locationIds = row?.id ? [row.id] : ids.value;
  proxy.$modal
    .confirm('是否确认删除位置编号为"' + locationIds + '"的数据项?')
    .then(() => {
      return delBatchLocation(locationIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
}

/** 设备搜索 */
function handleDeviceSearch(query: string) {
  if (query) {
    deviceLoading.value = true;
    getlistDevice({
      pageNum: 1,
      pageSize: 10,
      deviceName: query
    }).then((response) => {
      deviceOptions.value = response.rows;
      deviceLoading.value = false;
    });
  } else {
    deviceOptions.value = [];
  }
}

/** 设备滚动加载 */
function handleDeviceScroll(e: any) {
  const { scrollTop, scrollHeight, clientHeight } = e.target;
  if (scrollHeight - scrollTop - clientHeight < 50) {
    if (!deviceLoading.value) {
      handleDeviceSearch(queryParams.value.locationName || '');
    }
  }
}

/** 分页大小改变 */
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val;
  getList();
}

/** 当前页改变 */
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val;
  getList();
}

// 设备相关
const deviceLoading = ref(false);
const deviceOptions = ref<DeviceVO[]>([]);

/** 修改按钮操作 */
function handleUpdate(row: LocationVo) {
  proxy.$router.push({ path: '/vending/locationEdit/index', query: { type: 'update', id: row.id } });
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .box-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 18px;
        font-weight: bold;
      }
    }
  }

  .search-form {
    margin-bottom: 20px;
  }

  .table-container {
    .location-table {
      margin-bottom: 20px;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
